import React, {
  useEffect,
  useState,
  useRef,
  useContext,
  createContext,
} from "react";
import {
  getProductList,
  updateSeckill,
  updateRecommend,
  getProductCategory,
  getProductFilter,
} from "@/api/product/product";
import { Table, Switch, Space, Select, Input, Button, Form } from "antd";
import { useSize } from "ahooks";
import usePagination from "@/hooks/usePagination";

const EditableContext = createContext(null);
const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};
const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext);
  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);
  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };
  const save = async () => {
    try {
      const value = await form.validateFields();
      const a = value.originprice.replace(/[^\d]/g, "")
      toggleEdit();
      handleSave({
        ...record,
        originprice: a
      });
    } catch (errInfo) {
      console.log("Save failed:", errInfo);
    }
  };
  let childNode = children;
  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{
          paddingRight: 24,
        }}
        onClick={toggleEdit}
      >
        {children}
      </div>
    );
  }
  return <td {...restProps}>{childNode}</td>;
};

export default function Home() {
  const [productList, setProductList] = useState([]);
  const flagRef = useRef(true);

  //获取商品列表数据
  const getProductListDate = () => {
    getProductList().then((res) => {
      res.data.data = res.data.data.map((item) => {
        return {
          ...item,
          key: item.proid,
        };
      });
      // console.log(res.data.data);
      setProductList(res.data.data);
      //判断数据是否小于分页数，如果小于则不再请求数据 用于判断是否还有下一页
      if (
        res.data.data.length <=
        pagination.pageSize * (pagination.current - 1)
      ) {
        flagRef.current = false;
      }
    });
  };

  //组件挂载时获取数据
  useEffect(() => {
    getProductListDate();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  //使用usePagination自定义分页
  const pagination =
    usePagination(/* {
    callback() {
      flagRef.current = true;
    },
  } */);
  //使用ahooks中的useSize获取页面高度
  const size = useSize(document.querySelector("body"));

  const defaultHeight = document.body.offsetHeight;

  //表格列配置
  const defaultColumns = [
    {
      title: "序号",
      width: 150,

      fixed: "left",
      render: (text, record, index) =>
        `${pagination.pageSize *
        (flagRef.current
          ? pagination.current - 1
          : pagination.current - 2) +
        index +
        1
        }`,
    },

    {
      /* Breakpoint = 'xxl' | 'xl' | 'lg' | 'md' | 'sm' | 'xs'; */
      title: "商品图片",

      dataIndex: "img1",
      render: (text, record, index) => {
        return (
          <img src={text} alt="" style={{ width: "50px", height: "50px" }} />
        );
      },
    },
    {
      title: "商品名称",
      responsive: ["xl"],
      ellipsis: true,
      // editable: true,
      dataIndex: "proname",
    },
    {
      title: "商品价格/元",
      editable: true,
      dataIndex: "originprice",
      sorter: (a, b) => a.originprice - b.originprice,
    },
    {
      title: "折扣",
      responsive: ["lg"],
      dataIndex: "discount",
    },
    {
      title: "销售额/元",
      responsive: ["lg"],
      dataIndex: "sales",
      sorter: (a, b) => a.sales - b.sales,
    },
    {
      title: "商品库存",
      editable: true,
      dataIndex: "stock",
    },
    {
      title: "产品推荐",
      dataIndex: "isrecommend",
      render: (text, record) => {
        return (
          <Switch
            checkedChildren="开启"
            unCheckedChildren="关闭"
            defaultChecked={text === 1}
            onChange={() => {
              //调用修改推荐状态的接口
              updateRecommend({
                proid: record.proid,
                flag: text === 0,
              }).then(() => {
                getProductListDate();
                // console.log(text === 0);
              });
            }}
          />
        );
      },
    },
    {
      title: "产品秒杀",
      dataIndex: "isseckill",
      responsive: ["lg"],

      ellipsis: true,
      render: (text, record) => {
        return (
          <Switch
            checkedChildren="开启"
            unCheckedChildren="关闭"
            defaultChecked={text === 1}
            onChange={() => {
              updateSeckill({
                proid: record.proid,
                flag: text === 0,
              }).then(() => {
                getProductListDate();
                // console.log(text === 0);
              });
            }}
          />
        );
      },
    },
  ];

  //筛选功能
  const [categoryList, setCategoryList] = useState([]);
  const [category, setCategory] = useState("");
  const [search, setSearch] = useState("");

  useEffect(() => {
    getProductCategory().then((res) => {
      setCategoryList(res.data.data);
    });
  }, []);

  //、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

  const handleSave = (row) => {
    const newData = [...productList];

    const index = newData.findIndex((item) => {
      // console.log(item);
      return row.key === item.key;
    });
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    setProductList(newData);
  };
  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };
  const columns = defaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave,
      }),
    };
  });

  return (
    //实现筛选功能
    <Space direction="vertical">
      <Space>
        <Select value={category} onChange={(value) => setCategory(value)}>
          <Select.Option value="">全部</Select.Option>
          {categoryList.map((item, index) => {
            return (
              <Select.Option key={index} value={item}>
                {item}
              </Select.Option>
            );
          })}
        </Select>
        <Input
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        ></Input>
        <Button
          type="primary"
          onClick={() => {
            getProductFilter({ category, search }).then((res) =>
              setProductList(res.data.data)
            );
          }}
        >
          搜索
        </Button>
      </Space>
      <Table
        components={components}
        rowKey={(record) => record.key}
        columns={columns}
        scroll={{
          y: (size ? size.height : defaultHeight) - 310,
        }}
        pagination={pagination}
        dataSource={productList}
        style={{ width: "99%" }}
      />
    </Space>
  );
}
